<template>
  <el-dialog 
    :title="formData.id ? '编辑违法记录' : '新增违法记录'" 
    :visible.sync="visible" 
    width="50%"
    :close-on-click-modal="false"
    :before-close="handleClose">
    <el-form :model="formData" :rules="rules" ref="violationForm" label-width="100px">
      <el-form-item label="车牌号" prop="carId">
        <el-input v-model="formData.carId" placeholder="请输入车牌号，留空则显示为无法识别"></el-input>
      </el-form-item>
      
      <el-form-item label="违法类型" prop="violationType">
        <el-select v-model="formData.violationType" placeholder="请选择违法类型">
          <el-option 
            v-for="item in violationTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="违法地点" prop="location">
        <el-input v-model="formData.location" placeholder="请输入违法地点"></el-input>
      </el-form-item>
      
      <el-form-item label="预警等级" prop="warningLevel">
        <el-select v-model="formData.warningLevel" placeholder="请选择预警等级">
          <el-option label="低" :value="1"></el-option>
          <el-option label="中" :value="2"></el-option>
          <el-option label="高" :value="3"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="违法描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入违法描述"></el-input>
      </el-form-item>
      
      <el-form-item label="证据图片">
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :file-list="fileList"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addViolation } from '@/api/violation'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      default: () => ({
        violationType: '',
        description: '',
        location: '克拉玛依市克拉玛依区文轩路',
        status: 0,
        type: 1,
        warningLevel: 1
      })
    }
  },
  data() {
    return {
      submitting: false,
      fileList: [],
      violationTypes: [
        { label: '超速', value: 1 },
        { label: '违规转弯', value: 2 },
        { label: '压线', value: 3 },
        { label: '机动车闯红灯', value: 4 },
        { label: '行人闯红灯', value: 5 }
      ],
      rules: {
        violationType: [
          { required: true, message: '请选择违法类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请填写违法描述', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请填写违法地点', trigger: 'blur' }
        ],
        warningLevel: [
          { required: true, message: '请选择预警等级', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      if (val && this.formData.imagePath) {
        // 如果有图片路径，添加到文件列表中
        this.fileList = [{
          name: '违法图片',
          url: this.formData.imagePath
        }];
      } else if (val && this.formData.evidenceImages && this.formData.evidenceImages.length > 0) {
        // 如果有证据图片数组，添加到文件列表中
        this.fileList = this.formData.evidenceImages.map((url, index) => ({
          name: `违法图片${index + 1}`,
          url
        }));
      } else if (!val) {
        // 关闭对话框时清空文件列表
        this.fileList = [];
      }
    }
  },
  methods: {
    handleClose() {
      this.$refs.violationForm?.resetFields();
      this.$emit('update:visible', false);
    },
    
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },
    
    handleSubmit() {
      this.$refs.violationForm.validate(valid => {
        if (!valid) {
          return false;
        }
        
        this.submitting = true;
        
        // 准备提交的数据
        const submitData = {
          ...this.formData,
          // 根据违法类型设置违法主体：5是行人闯红灯，其他是车辆
          type: this.formData.violationType === 5 ? 2 : 1,
          // 设置状态为未读
          status: 0,
          // 如果有新上传的图片，处理图片数据
          evidenceImages: this.fileList.map(file => file.url || URL.createObjectURL(file.raw))
        };
        
        addViolation(submitData).then(response => {
          this.$message.success('保存成功');
          this.$emit('update:visible', false);
          this.$emit('refresh');
        }).catch(error => {
          console.error('保存失败:', error);
          this.$message.error('保存失败: ' + (error.message || '未知错误'));
        }).finally(() => {
          this.submitting = false;
        });
      });
    }
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>